<?php

/**
 * @filename ExpireController.php
 * @author qiankun<qiankun@dodoca.com>
 * @datetime 2017/5/11
 * @description 过期会员/失效会员
 */
class Member_ExpireController extends SellerController
{
    protected $userId;
    protected $sellerId;
    protected $shopId;
    protected $role;

    public function init()
    {
        parent::init();
        $this->userId = intval($this->getCurrentUser()->get('id'));
        $this->shopId = intval($this->getCurrentUser()->getShopId());
        $this->sellerId = intval($this->getCurrentUser()->getSellerId());
        $this->role = intval($this->getCurrentUser()->getRole());  //账户类型（1：商户账号；2：超级；3：店长；4：收银员）
    }

    /**
     * @author qiankun
     * @Fuction name indexAction
     * @description 失效会员
     */
    public function indexAction()
    {
        //基本条件
        $params = $this->_request->getQuery();
        $page = max(1, intval($params['page']));

        $pageSize = 10;
        $shopId = $this->getCurrentUser()->getShopId();

        $sellerId = $this->getCurrentUser()->getSellerId();
        $params['seller_id'] = $sellerId;
        if(!$this->getCurrentUser()->isChiefShop())
        {
            $params['shop_id'] = $shopId;
            $fansWhere['shop_id'] = $shopId;
        }
        else
        {
            $shopId = 0;
        }
        $importModel = new Statistics_MemberImportModel();
        $memberImportFileModel = new Statistics_MemberImportFileModel();

        $payCardList = User_CardService::getExpireMemberListBySellerId($sellerId);
        $cardList = array();
        if($payCardList)
        {
        	foreach ($payCardList as $v)
        	{
        		$cardList[] = $v;
        	}
        }
        $shopFansModel = new U_ShopFansModel($sellerId);
        $fansWhere['seller_id'] = $sellerId;
        $fansArr = $shopFansModel->select($fansWhere, array('fans_id'));
        $fansIdArr = array();
        if(!empty($fansArr)) {
            foreach($fansArr as $key => $value){
                $fansIdArr[] = $value['fans_id'];
            }
        }
        $data = User_CardService::getMemberList($params, $page, $pageSize,$this->shopId);
        $count = $data['total'];
        $totalPage = ceil($count/$pageSize);
        Tool_Log::info('member_total','member_total',array('count'=>$count,'totalPage'=>$totalPage));
        $list = $data['list'];
        if(!empty($list))
        {
            $shop = $this->getCurrentUser()->getShop();
            if($shop['consumption_status'] == 1 || $this->getCurrentUser()->isChiefShop())
            {
                $shopId = $this->getCurrentUser()->getChiefShopId();
                $fansIdArr = array();
                foreach ($list as $k=>$v)
                {
                    $fansIdArr[] = $v['fans_id'];
                }
                $shopFansInfo = $shopFansModel->select(array('fans_id'=>array('in',$fansIdArr),'shop_id'=>$shopId),array('consumption','fans_id','integral'));
                //var_dump($shopFansInfo);
            }
            foreach($list as $k => $v)
            {
                //查询会员卡名称
                $cardInfo = User_CardService::getCardInfo($v['card_id']);
                $list[$k]['card_name'] = $cardInfo['card_name'];
                $beforeCardInfo = User_CardService::getCardInfo($v['before_card_id']);
                $list[$k]['old_card_name'] = $beforeCardInfo['card_name'];
                if($v['user_info'])
                {
                    $list[$k]['user_info'] = json_decode($v['user_info'], true);
                }
                if($shopFansInfo)
                {
                    foreach ($shopFansInfo as $key=>$val)
                    {
                        if($v['fans_id'] == $val['fans_id'])
                        {
                            $list[$k]['consumption'] = $val['consumption'];
                            $list[$k]['shop_integral'] = $val['integral'];
                        }
                    }
                }
            }
        }
        //获得excel基本数据
        $where = array(
            'status' => 2,
            'seller_id' => $sellerId,
            'shop_id' => $this->getCurrentUser()->getShopId()
        );
        if($importFile = $memberImportFileModel->find($where,array('id','create_time'),'id DESC'))
        {
            $importFile['create_time'] = date('Y-m-d H:i', $importFile['create_time']);
            $where = array('import_file_id' => $importFile['id'], 'status' => 2);//成功条数
            $successCount = $importModel->count($where);
            $where = array('import_file_id' => $importFile['id'], 'status' => 3);//失败条数
            $errorCount = $importModel->count($where);
        }
        //获得excel基本数据END

        //获得商户手机号
        $subUserModel = new U_SubUserModel();
        $where = array(
            'seller_id' => $this->sellerId,
            'type' => array('in','1,2'),
            'status' => 1,
            'phone' => array('neq','')
        );
        $subUser = $subUserModel->select($where,array('id','phone'));

        $coupon = Deposit_CouponService::manualCouponList($this->getCurrentUser()->getShopId(),1,3,'',1,500);
        //判断是否提示验证验证码
        $phoneKey = 'qualifiedPhone_' . $this->getCurrentUser()->get('id');
        $phoneKey = mc_get($phoneKey);
        $hasCheckPhone = isset($phoneKey)? 1 : 0;//1为不验证
        $data = array(
            'count' => $count,
            'params' => $params,
            'totalPage' => $totalPage,
            'page' => $page,
            'member_list' => $list,
            'coupon'=>$coupon['lists'],
            'successCount' => $successCount,
            'errorCount' => $errorCount,
            'importFile' => $importFile,
            'role' => $this->role,
            'subUser' => $subUser,
            'payCardList' => $cardList,
            'hasCheckPhone' => $hasCheckPhone,
            'is_pay' => count($cardList),
            'webUrl' => WEB_DOMAIN
        );
        $this->assign('loadModuleScript', true);
        $this->display($data, 'member/expire/index.html');
    }

    /**
     * @author qiankun
     * @Fuction name getSmsAction
     * @description 获取短信验证码
     */
    public function ajaxGetSmsAction()
    {
        try
        {
            if (!$this->_request->isXmlHttpRequest() || !$this->_request->isPost()) {
                throw new Exception('非法访问');
            }
            $mobile = trim($this->_request->getPost('phone'));
            if(!Tool_Validator::isCellphone($mobile)){
                throw new Exception('请输入正确的手机号码！');
            }
            $obj = SmsService::getInstance()->setMobile($mobile)->setSeller($this->sellerId)->setTpl('common')->send();
            if($obj){
                $this->ajaxReturn(array(
                    'code' => 1,
                    'msg' => '发送成功',
                ));
            }
        }
        catch(Exception $e){
            $this->ajaxReturn(array(
                'code' => -1,
                'msg' => $e->getMessage()
            ));
        }
    }

    /**
     * @author qiankun
     * @Fuction name checkPhoneAction
     * @description 批量修改付费会员等级
     */
    public function ajaxVerifyPhoneAction()
    {
        try
        {
            if (!$this->_request->isXmlHttpRequest() || !$this->_request->isPost())
            {
                throw new Exception('非法访问');
            }
            //检查权限
            if($this->role != 2)
            {
                throw new Exception('只有商户账号和超级管理员账户可以修改会员等级');
            }
            $postData = $this->_request->getPost();
            $phone = $postData['phone'];
            $imgCode = $postData['img_code'];
            $codes = $postData['codes'];
            $cardId = intval($postData['card_id']);
            $fansIds = $postData['fansIds'];

            //判断是否提示验证验证码
            $phoneKey = 'qualifiedPhone_' . $this->getCurrentUser()->get('id');
            $phoneKeys = mc_get($phoneKey);
            $hasCheckPhone = isset($phoneKeys)? 1 : 0;//1为不验证
            if(!$hasCheckPhone)
            {
                if(!$phone)
                {
                    throw new Exception('请填写手机号');
                }
                if(!$codes)
                {
                    throw new Exception('请填写验证码');
                }
            }
            if(!$imgCode || !$fansIds)
            {
                throw new Exception('提交信息不完整');
            }

            if(!SmsService::validCode($phone, 'common', $codes) && $hasCheckPhone != 1)
            {
                throw new Exception('短信验证码不正确');
            }
            mc_set($phoneKey, 1,15*60);//设置有效期15分钟
            if($imgCode != get_session('imgcode')){
                throw new Exception('请输入正确的验证码');
            }
            $fansModel = new U_FansModel($this->sellerId);
            $memberCardModel = new U_CardAttrModel();
            $userMemberModel = new U_MemberCardModel();
            $shopFansModel = new U_ShopFansModel($this->sellerId);
            //设置为非会员
            if($postData['card_id'] == 0)
            {
                $data['card_id'] = 0;
                $data['status'] = 4;
                $data['card_name'] = '非会员';
                $data['pay_type'] = 5;
                $data['update_time'] = SYS_TIME;
                //更新人数
                if($fansIds)
                {
                    $fansIdArray = explode(',', $fansIds);
                    //检测是否有删除权限
                    foreach($fansIdArray as $key => $value)
                    {
                        if(!intval($value))
                        {
                            throw new Exception('数据非法');
                        }
                        if($oldCardId = $userMemberModel->find(array('fans_id' => $value,'seller_id'=>$this->sellerId),array('card_id')))
                        {
                            //更新会员人数
                            User_CardService::memberCountAlter($oldCardId, -1);
                        }
                        $data['before_card_id'] = $oldCardId;
                        $where = array(
                            'fans_id' => $value,
                            'seller_id' => $this->sellerId
                        );
                        $userMemberModel->updateData($data,$where);
                        //更新为非会员状态
                        $where = array(
                            'fans_id' => intval($value),
                            'seller_id' => $this->sellerId,
                            'shop_id' => $this->shopId
                        );
                        $shopFansModel->updateData(array('is_member' => 0),$where);
                    }
                }
                $data = array(
                    'level' => '0',
                    'card_id' => '0'
                );
                $fansModel->updateData($data,array('id'=>$fansIds));
                $this->ajaxReturn(
                    array(
                        'code' => '1000', 'msg' => "更新成功"
                    )
                );
            }
            $where = array('id' => $cardId);
            if(!$memberCard = $memberCardModel->find($where,array('id','level','type','pay_start_time','pay_end_time','pay_month')))
            {
                throw new Exception('无此会员卡');
            }
            if($fansIds)
            {
                $fansIdArray = explode(',', $fansIds);
                //检测是否有修改权限
                foreach($fansIdArray as $key => $value)
                {
                    if(intval($value))
                    {

                        if(!$userMemberModel->count(array('fans_id' => intval($value),'seller_id'=>$this->sellerId,'pay_type'=>array('in','2,3,4,5'))))
                        {
                            throw new Exception('只能修改付费会员');
                        }
                        //只能修改付费会员
                        if(!$memberCardModel->count(array('id' => $cardId,'type'=>array('in','2,3,4,5'))))
                        {
                            throw new Exception('只能修改为付费会员');
                        }
                        $ids[] = intval($value);
                    }
                    else
                    {
                        unset($fansIdArray[$key]);
                    }
                }
                //批量修改
                if($ids)
                {
                    //处理不同类型的时间状态
                    switch($memberCard['type'])
                    {
                        case 1:
                            throw new Exception('付费会员卡不能改为免费会员卡');
                            break;
                        case 2:
                            $data['pay_type'] = $memberCard['type'];
                            $data['status'] = 1;
                            break;
                        case 3:
                            $data['pay_start_time'] = SYS_TIME;
                            $data['pay_end_time'] = strtotime('+'.$memberCard['pay_month'].' month');
                            $data['pay_type'] = $memberCard['type'];
                            $data['status'] = 1;
                            break;
                        case 4:
                            $data['pay_start_time'] = $memberCard['pay_start_time'];
                            $data['pay_end_time'] = $memberCard['pay_end_time'];
                            $data['pay_type'] = $memberCard['type'];
                            $data['status'] = 1;
                            break;
                        default:
                            throw new Exception('未选择对应的付费类型');
                    }

                    $data['card_id'] = $cardId;
                    $data['update_time'] = SYS_TIME;
                    $data['shop_id'] = $this->shopId;
                    $ids = implode(',',$ids);
                    $where = array('id' => array('in',$ids));
                    $fansData = array(
                        'level' => $memberCard['level'],
                        'card_id' => $cardId
                    );
                    $fansModel->updateData($fansData,$where);
                    foreach($fansIdArray as $key => $value)
                    {
                        //更新会员数量
                        if($oldCardId = $userMemberModel->find(array('fans_id' => $fansIds,'seller_id'=>$this->sellerId),array('card_id')))
                        {
                            User_CardService::memberCountAlter($oldCardId, -1);
                        }
                        //修改会员信息
                        $where = array(
                            'fans_id' => intval($value),
                            'seller_id' => $this->sellerId
                        );
                        $data['card_id'] = $cardId;
                        $data['before_card_id'] = $oldCardId;
                        $data['update_time'] = SYS_TIME;
                        $userMemberModel->updateData($data,$where);
                        //非会员修改为会员
                        $where = array(
                            'fans_id' => intval($value),
                            'seller_id' => $this->sellerId,
                            'shop_id' => $this->shopId
                        );
                        $shopFansModel->updateData(array('is_member'=>1),$where);

                        User_CardService::memberCountAlter($cardId, 1);
                    }
                    $this->ajaxReturn(
                        array(
                            'code' => '1000', 'msg' => "更新成功"
                        )
                    );
                }
                else
                {
                    throw new Exception('无效的数据');
                }
            }
            else
            {
                throw new Exception('无更新数据');
            }
        }
        catch (Exception $e)
        {
            $this->ajaxReturn(array('code'=>0,'msg'=>$e->getMessage()));
        }

    }
    /**
     * @author qiankun
     * @Fuction name ajaxEditLevelAction
     * @description 单个修改会员等级
     */
    public function ajaxEditLevelAction()
    {
        try
        {
            if(!$this->_request->isXmlHttpRequest())
            {
                throw new Exception('非法请求');
            }
            //检查权限
            if($this->role != 2)
            {
                throw new Exception('只有商户账号和超级管理员账户可以修改会员等级');
            }
            $params = $this->_request->getPost();
            $fansModel = new U_FansModel($this->sellerId);
            $memberCardModel = new U_CardAttrModel();
            $userMemberModel = new U_MemberCardModel();
            $shopFansModel = new U_ShopFansModel($this->sellerId);
            $cardId = intval($params['card_id']);
            $fansIds = intval($params['fansIds']);
            if($params['card_id'] == '' || !$fansIds)
            {
                throw new Exception('缺少参数');
            }

            $oldCardId = $userMemberModel->find(array('fans_id' => $fansIds,'seller_id'=>$this->sellerId),array('card_id'));
            //设置为非会员
            if($cardId == 0)
            {
                $where = array('fans_id' => $fansIds);
                $data['card_id'] = 0;
                $data['before_card_id'] = $oldCardId;
                $data['pay_type'] = 5;
                $data['status'] = 4;
                $data['card_name'] = '非会员';
                $data['update_time'] = SYS_TIME;
                $userMemberModel->updateData($data,$where);
                //更新会员人数
                User_CardService::memberCountAlter($oldCardId, -1);

                $data = array('level' => '0','card_id' => '0');
                $fansModel->updateData($data,array('id'=>$fansIds));

                $where = array(
                    'fans_id' => $fansIds,
                    'seller_id' => $this->sellerId
                );
                $shopFansModel->updateData(array('is_member' => 0),$where);

                $this->ajaxReturn(
                    array(
                        'code' => '1', 'msg' => "更新成功"
                    )
                );
            }
            $where = array(
                'id' => $cardId,
                'seller_id' => $this->sellerId
            );
            if(!$memberCard = $memberCardModel->find($where,array('id','level','type','pay_start_time','pay_end_time','pay_month','card_name')))
            {
                throw new Exception('无此会员卡');
            }

            //只能修改付费会员
            //var_dump($params);
            if(!$oldCard = $userMemberModel->find(array('fans_id' => $fansIds,'seller_id'=>$this->sellerId,'pay_type'=>array('in','2,3,4,5'))))
            {
                throw new Exception('只能修改付费会员');
            }
            //只能修改付费会员
            if(!$memberCardModel->count(array('id' => $cardId,'type'=>array('in','2,3,4,5'))))
            {
                throw new Exception('只能修改为付费会员');
            }
            //更改会员时间期限
            switch($memberCard['type'])
            {
                case 1:
                    throw new Exception('付费会员卡不能改为免费会员卡');
                    break;
                case 2:
                    $data['pay_type'] = $memberCard['type'];
                    break;
                case 3:
                    $data['pay_start_time'] = SYS_TIME;
                    $data['pay_end_time'] = strtotime('+'.$memberCard['pay_month'].' month');
                    $data['pay_type'] = $memberCard['type'];
                    break;
                case 4:
                    $data['pay_start_time'] = $memberCard['pay_start_time'];
                    $data['pay_end_time'] = $memberCard['pay_end_time'];
                    $data['pay_type'] = $memberCard['type'];
                    break;
                default:
                    throw new Exception('未选择对应的付费类型');
            }

            $where = array(
                'fans_id' => $fansIds,
                'seller_id' => $this->sellerId
            );
            $data['status'] = 1;
            $data['card_name'] = $memberCard['card_name'];
            $data['card_id'] = $cardId;
            $data['before_card_id'] = $oldCard['card_id'];
            $data['update_time'] = SYS_TIME;
            $data['shop_id'] = $this->shopId;
            $userMemberModel->updateData($data,$where);

            //更新数量
            User_CardService::memberCountAlter($cardId, 1);
            User_CardService::memberCountAlter($oldCardId, -1);

            $data = array('level'=>$memberCard['level'],'card_id'=>$cardId);
            $fansModel->updateData($data,array('id'=>$fansIds,'seller_id' => $this->sellerId));
            $where = array(
                'fans_id' => $fansIds,
                'seller_id' => $this->sellerId,
                'shop_id' => $this->shopId
            );

            $shopFansModel->updateData(array('is_member' => 1),$where);

            $this->ajaxReturn(
                array(
                    'code' => '1', 'msg' => "更新成功"
                )
            );

        }
        catch (Exception $e)
        {
            $this->ajaxReturn(array('code'=>0,'msg'=>$e->getMessage()));
        }

    }

    /**
     * @author qiankun
     * @Fuction name getCardSelectListAction
     * @description 获得付费会员有效等级列表
     */
    public function ajaxCardSelectAction()
    {
        try
        {
        	//$fid = trim($this->_request->getPost('fid'));
        	//$member = User_CardService::isSetMember($fid, $this->sellerId);
        	$payCardList = User_CardService::getExpireMemberListBySellerId($this->sellerId);
        	/* if(!$member['is_set'])
        	{
        		throw new Exception('会员错误');
        	}
        	if(in_array($member['status'], array(3,4)))
        	{
        		$oldCardId = $member['before_card_id'];
        	}
        	else 
        	{
        		$oldCardId = $member['card_id'];
        	}
        	if($oldCardId)
        	{
        		$cardInfo = User_CardService::getCardInfo($oldCardId);
        	}
        	
            
            if($cardInfo)
            {
            	$list[0] = $cardInfo;
            }
            else 
            {
            	$list = array();
            } */
        	$list = array();
            if($payCardList)
            {
            	foreach ($payCardList as $v)
            	{
            		$list[] = $v;
            	}
            }
            
            $this->ajaxReturn(array('code'=>1,'msg'=>'success','data'=>$list));
        }
        catch (Exception $e)
        {
            $this->ajaxReturn(array('code'=>0,'msg'=>$e->getMessage()));
        }
    }


}